package com.neusoft.cmsprojects.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

public class PictuerUploadDeleteUtil {
	public static String uploadPicture(File file) throws IOException{
		System.out.println("1211");
		InputStream is = new FileInputStream(file);
		String path = ServletActionContext.getServletContext().getRealPath("/");
		System.out.println("5433");
		path = path+"projectImages";
		path=path.replaceAll("%20"," "); 
		String fileName = DateUtil.getDate()+Math.round(Math.random() * 900) + 100 +"w"+ Math.round(Math.random() * 900  )+"z"+ Math.round(Math.random() * 1000  ) + 100+"p.jpg";
		System.out.println("faqf");
		System.out.println(path);
		//System.out.println("fileName= " + fileName);
		
		HttpServletRequest rq = ServletActionContext.getRequest();
		String simgName = (String) rq.getSession().getAttribute("expertImg");
		
		//System.out.println("simgName= " + simgName);
		
		simgName = simgName + fileName + ",";
		rq.getSession().setAttribute("expertImg", simgName);
		
		File outputFile = new File(path,fileName);
		OutputStream os = new FileOutputStream(outputFile);
		
		
		
		
		byte[] temp = new byte[1024];
		int getByte = 0;
		while((getByte=is.read(temp))>0){
			os.write(temp,0, getByte);
		}
		
		is.close();
		os.close();
		
		return fileName;
	}
	
	public static void deletePicture(String picture){
		String path = ServletActionContext.getServletContext().getRealPath("/");
		path=path.replaceAll("%20"," "); 
		path = path+"projectImages\\"+picture;
		File file = new File(path);
		
		if(!file.exists()){
			return;
		}else{
			if(file.isFile()){
				file.delete();
			}
		}
	}
}
